<template>
  <div :class="{'mt10': marginTop}" class="collet-container">
    <div style="display:flex;align-items:center;">
      <div><Title :title="title" /></div>
      <div class="tip-container">
        <tipIcon is-diy />
        <span class="text">{{ titleTip }}</span>
      </div>
      <span style="flex:1;"/>
      <PlainCreateBtn v-if="isEdit" style="width: 80px;" size="small" @click="addCollet">添加</PlainCreateBtn>
      <btnGroup
        v-if="!isEdit && accountType === 1 && (costBelong === 0 || costBelong === 5) && !showMobilePage"
        ref="btnGroupRef"
        :list="[
          {label:'导出收款信息', exportApi:'/admin/supplier/settle/export', exportName:'收款信息', beforeExport: exportBeforeExport, type: 'export'},
        ]"
      />
      <template v-if="!showMobilePage">
        <div v-if="showFillBtn" class="supplier-import-btn" @click="autoFill">一键填单</div>
        <MoreOpeator
          v-if="isEdit && accountType === 1 && (costBelong === 0 || costBelong === 5)"
          :list="[
            {label: '导入', type:'import', extendParams: {accountType: accountType}, accept:'.xls,.xlsx', complateSetData: importCallback, importApi:`admin/supplier/collectMoneyData/import`},
            {label: '模板下载', type: 'export', queryData:{ accountType: accountType }, auth: accountType === 1, exportApi:'/admin/supplier/collectMoneyData/template', exportName:'收款信息'},
          ]"
          style="margin-left: 10px;"
        />
      </template>
    </div>
    <div style="display: flex;align-items: center;justify-content: flex-end;">
      <btnGroup
        v-if="!isEdit && accountType === 1 && (costBelong === 0 || costBelong === 5) && showMobilePage"
        ref="btnGroupRef"
        :list="[
          {label:'导出收款信息', exportApi:'/admin/supplier/settle/export', exportName:'收款信息', beforeExport: exportBeforeExport, type: 'export'},
        ]"
      />
    </div>
    <div v-if="showMobilePage" class="mt12 flex-center mb12">
      <MoreOpeator
        v-if="isEdit && accountType === 1 && (costBelong === 0 || costBelong === 5)"
        :list="[
          {label: '导入', type:'import', extendParams: {accountType: accountType}, accept:'.xls,.xlsx', complateSetData: importCallback, importApi:`admin/supplier/collectMoneyData/import`},
          {label: '模板下载', type: 'export', queryData:{ accountType: accountType }, auth: accountType === 1, exportApi:'/admin/supplier/collectMoneyData/template', exportName:'收款信息'},
        ]"
        style="margin-left: 10px;"
      />
      <div v-if="showFillBtn" class="supplier-import-btn" @click="autoFill">一键填单</div>
    </div>
    <dataDisplay :data-list="dataList" :class="{'third-cell': dataList.length <= 3}" style="margin-top: 4px" />
    <dynamicEditTable
      v-if="switchShow"
      ref="dynamicEditTableRef"
      v-model="value"
      :show-add-btn="false"
      :default-params="initColletMoneyData"
      :list-setting="listSetting"
      :is-edit="isEdit"
      :extend-btn="isEditEvent?'remark':''"
      :list-data="isEdit ? value : widthdrawInfo.collectMoneyData?setLogText(widthdrawInfo.collectMoneyData.list || []):[]"
      open-page
      @extendEvent="openEditDialog"
      @changeInputNumberData="changeInputNumberData"
      @selectChange="selectChange"
      @changeValue="changeValue"
      @fetchAutocomplete="fetchAutocomplete"
      @autocompleteSelect="autocompleteSelect"
      @rateInputChange="rateInputChange"/>

    <!-- 编辑结算单名称和备注 -->
    <el-dialog v-if="isEditEvent" :class="{'mobile-page-dialog':showMobilePage}" :visible.sync="dialogEditVisible" :close-on-click-modal="false" class="small-common-dialog-size" @close="closeDialog">
      <Title title="编辑付款事项" />
      <div class="edit-main">
        <el-input v-model="editRemarkData.remark" :maxlength="500" size="small" placeholder="请输入说明" type="text" />
      </div>
      <div class="edit-dialog-btn">
        <el-button type="primary" size="small" @click="edit()">保存</el-button>
        <el-button type="info" size="small" class="cancel-btn-style" @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Title from '@/components/Title';
import dynamicEditTable from '@/components/Common/dynamicEditTable';
import { accountType1, accountType2 } from './data';
import { moneyFilter } from '@/filters/number';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import ImportButton from '@/components/ImportButton';
import ExportButton from '@/components/ExportButton';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import math from '@/utils/math';
// api
import { platformList } from '@/api/select';
import { accountList, autoFillList, editColletMoneyList, supplierInfo } from '@/api/supplier';
import ElMessage from '@/utils/message';
import incomeAmountIcon from '@/assets/chargeOffDetail/incomeAmount.png';
import chargeoffiIcon from '@/assets/chargeOffDetail/chargeoff_status.png';
import flowNumberIcon from '@/assets/chargeOffDetail/flowNumber.png';
import { showModal } from '@/utils/message';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import { mapState } from 'vuex';

export default {
  components: { Title, dynamicEditTable, btnGroup, ImportButton, ExportButton, MoreOpeator, dataDisplay },
  model: {
    prop: 'value',
    event: 'changeValue'
  },
  props: {
    value: {
      type: Array,
      default: () => {
        return [{}];
      }
    },
    accountType: {
      type: Number,
      default: 1 // 1:第三方账户 2: 对公银行账户
    },
    // 当选中账号请款：收款人列表按旧逻辑展示“账号+下单平台”
    // 当选中其他请款：收款人列表“账号+下单平台”改为“说明”
    requestFundsType: {
      type: Number,
      default: 0 // 0:账号请款 1: 其他请款
    },
    totalPrice: { // 结算金额
      type: Number | String,
      default: null
    },
    isSelectOrder: {
      type: Boolean,
      default: false
    },
    selectCost: { // 当第二步没有生成草稿时，本地通过这个属性进行一键填充
      type: Array,
      default: null
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    fontSize: {
      type: String,
      default: '20px'
    },
    widthdrawInfo: {
      type: Object,
      default: () => {
        return {};
      }
    },
    examinId: {
      type: String | Number,
      default: null
    },
    // costBelong  0:渠道订单 1:项目订单 2:商务订单 3:营销授权 5:项目渠道单
    costBelong: {
      type: Number,
      default: 0
    },
    supplierId: {
      type: Number | String,
      default: null
    },
    settleId: {
      type: Number | String,
      default: null
    },
    isEditEvent: { // 编辑说明事件，当开启该事件时，可编辑结算单名称、备注、收款列表说明
      type: Boolean,
      default: false
    },
    isNotOrder: { // 是否为非订单请款
      type: Boolean,
      default: false
    },
    isCommerce: { // 是否为有赞供应商
      type: Boolean,
      default: false
    },
    marginTop: { // 距离顶部距离
      type: Number,
      default: 1
    },
    stepOneData: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      incomeAmountIcon, chargeoffiIcon, flowNumberIcon,
      orderPlatformOption: [],
      importLoading: false,
      accountType1,
      accountType2,
      switchShow: true,
      actualAmountTotal: '',
      receivedAmountTotal: '',
      editRemarkData: {},
      dialogEditVisible: false,
      supplierRate: null
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    title() {
      // return this.accountType === 1 ? '收款信息' : '付款事项';
      return '收款信息';
    },
    titleTip() {
      const settlementMethod = this.stepOneData.settlementMethod;
      return settlementMethod === 1 ? '一次结算：实付金额必须等于订单结算总金额' : '多次结算：本次结算实付金额必须小于等于订单结算总金额';
    },
    listSetting() {
      const accountType1Data = JSON.parse(JSON.stringify(this.accountType1));
      const accountType2Data = JSON.parse(JSON.stringify(this.accountType2));
      const listSettingData = this.accountType === 1 ? accountType1Data : accountType2Data;
      // 当选中账号请款：收款人列表按旧逻辑展示“账号+下单平台”
      // 当选中其他请款：收款人列表“账号+下单平台”改为“说明”
      if (this.stepOneData.process === 4 || [3, 4].includes(this.widthdrawInfo.examineStatus)) {
        // 审批完成或者已撤销收款账号加密
        // examineStatus，是单个审批单的审批状态 3:已作废 4:审批完成
        listSettingData.forEach(i => {
          if (i.keyword === 'payNum') {
            i.showType = 'secret';
          }
        });
      }

      if (this.requestFundsType === 1) {
        listSettingData.splice(0, 2, {
          label: '付款事项',
          width: '200px',
          type: 'inputText',
          isRequired: true,
          keyword: 'remark'
        });
      }
      return listSettingData;
    },
    settlementAmountTotal() {
      let list = [];
      if (this.isEdit) {
        list = this.value;
      } else if (this.widthdrawInfo.collectMoneyData && this.widthdrawInfo.collectMoneyData.list) {
        list = this.widthdrawInfo.collectMoneyData.list;
      }
      let total = null;
      list.forEach(i => {
        if (i.settlementAmount || i.settlementAmount === 0) {
          const totalPrice = Number(total) || 0;
          total = math.add(totalPrice, Number(i.settlementAmount));
        }
      });
      this.actualAmountTotalChange();
      return (total || total === 0) ? this.moneyFilter(total, true, '', true) : '';
    },
    isInvite() {
      return !!this.stepOneData.isInvite;
    },
    dataList() {
      const arr = [];
      if (!this.isNotOrder) {
        let totalPrice = '';
        if (this.isEdit) {
          totalPrice = this.totalPrice || this.totalPrice === 0 ? moneyFilter((this.totalPrice / 100), true, '', true) : '';
        } else {
          totalPrice = this.widthdrawInfo.collectMoneyData ? moneyFilter((this.widthdrawInfo.collectMoneyData.settlementAmountTotal / 100), true, '', true) : '';
        }
        /**
         * 1、totalPrice 取的是结算详情（admin/supplier/settle/:id）的 totalPrice
         * 2、settlementAmountTotal 取的是当前审批单详情（admin/supplier/currentWithdraw/info/:id）的 collectMoneyData.settlementAmountTotal
         * 3、单位都是分，且字段完全一样
         * 4、它们都代表订单列表中所选择订单和成本的结算金额之和，其中订单取的是“结算金额（costPrice）”字段
         * 成本取的是“含税成本(taxCost)”字段
         */
        arr.push({ icon: incomeAmountIcon, label: '订单结算金额(总)', data: totalPrice, unit: '元' });
      }
      arr.push({ icon: chargeoffiIcon, label: '本次结算金额(总)', data: this.settlementAmountTotal, unit: '元' });
      if (this.accountType === 1) {
        arr.push({ icon: chargeoffiIcon, label: '对方到手金额(总)', data: this.receivedAmountTotal, unit: '元' });
      }
      arr.push({ icon: flowNumberIcon, label: '本次实付金额(总)', data: this.actualAmountTotal, unit: '元' });
      return arr;
    },
    isAccountSettle() { // 待办账号结算
      return !!this.$route.query.isAccountSettle;
    },
    showFillBtn() {
      // costBelong 0:渠道订单 5:项目渠道订单
      return (this.isSelectOrder && this.isEdit && (this.costBelong === 0 || this.costBelong === 5 || this.requestFundsType === 1)) || this.isAccountSettle;
    },
    initColletMoneyData() {
      return { // 收款人列表初始值
        collectMoneyType: 0, priceRate: this.supplierRate || 1.065,
        _disabledObj: { actualAmount: true, withdrawAmount: true }
      };
    }
  },
  watch: {
    accountType(newV) {
      this.switchShow = false;
      this.$nextTick(() => {
        this.switchShow = true;
      });
      if (this.isEdit) {
        this.initData();
      }
    },
    'stepOneData.supplierId': {
      handler(val) {
        if (val) {
          this.getSupplierInfo(val);
        }
      },
      immediate: true
    }
  },
  created() {
    this.platformList();
    // this.initData();
  },
  methods: {
    moneyFilter,
    validate() {
      return new Promise((resolve, reject) => {
        this.$refs.dynamicEditTableRef.validate().then(() => {
          resolve(true);
        }).catch(() => {
          reject('【收款信息】请填写完整');
        });
      });
    },
    addCollet() {
      const extendParams = {};
      if (this.value.length) extendParams.priceRate = this.value[0].priceRate;
      this.$refs.dynamicEditTableRef.addValue(false, extendParams);
    },
    changeValue(value) {
      this.$emit('changeValue', value);
    },
    async getSupplierInfo(id) {
      const res = await supplierInfo(id);
      if (res.code === 200) {
        const { hasRate, priceRate } = res.data;
        if (hasRate) {
          this.supplierRate = priceRate;
          this.$emit('setSupplierRate', priceRate);
        }
      }
    },
    actualAmountTotalChange() {
      let list = [];
      if (this.isEdit) {
        list = this.value;
      } else if (this.widthdrawInfo.collectMoneyData && this.widthdrawInfo.collectMoneyData.list) {
        list = this.widthdrawInfo.collectMoneyData.list;
      }
      let total = null;
      let receivedAmountTotal = null;
      list.forEach(i => {
        if (i.actualAmount || i.actualAmount === 0) {
          const totalPrice = Number(total) || 0;
          total = math.add(totalPrice, Number(i.actualAmount));
        }
        if (i.withdrawAmount || i.withdrawAmount === 0) {
          const totalPrice = Number(receivedAmountTotal) || 0;
          receivedAmountTotal = math.add(totalPrice, Number(i.withdrawAmount));
        }
      });

      this.actualAmountTotal = (total || total === 0) ? this.moneyFilter(total, true, '', true) : '';
      this.receivedAmountTotal = (receivedAmountTotal || receivedAmountTotal === 0) ? this.moneyFilter(receivedAmountTotal, true, '', true) : '';
    },
    // 下拉选项改变时
    selectChange({ item, key }) {
      /**
        ①当选择请款类型为全款
          禁用达人到手金额和实付金额
        ②当前选择请款类型为预付款、部分款、尾款
          启用达人到手金额和实付金额
          当修改达人到手金额，实付金额=达人到手金额*费率
          当修改实付金额，达人到手金额=实付金额/费率
          当修改费率，实付金额=达人到手金额*费率
       */
      if (key === 'collectMoneyType') {
        this.isDisabled(item);
        this.changeInputNumberData({ item, key: 'settlementAmount' });
      }
    },
    initData() {
      this.$nextTick(() => {
        if (this.value) {
          this.value.forEach((item) => {
            this.isDisabled(item);
          });
        }
      });
    },
    isDisabled(item) {
      if (item.collectMoneyType === 0) { // 请款类型为全款
        this.$set(item, '_disabledObj', { actualAmount: true });
        if (this.accountType === 1) {
          this.$set(item._disabledObj, 'withdrawAmount', true);
        }
      } else {
        item._disabledObj = {};
      }
    },
    /**
     * 事件
     */
    fetchAutocomplete({ value, cb, item, settingItem }) {
      if (settingItem.keyword === 'payName') {
        let type = (this.costBelong === 2 || this.costBelong === 3) ? 2 : 1;
        if (this.isCommerce) { // 如果是有赞
          type = 3;
        }
        const params = {
          page: 1,
          perPage: 100,
          type: type,
          id: this.supplierId,
          supplierId: this.supplierId
        };
        if (value) params.payName = value;
        accountList(params).then(res => {
          if (res.code === 200) {
            res.data.items.forEach(i => {
              const str = i.payNum.slice(-4);
              i.value = `${i.payName}(${str})`;
            });
            cb(res.data.items);
          } else {
            cb([]);
          }
        }).catch(() => {
          cb([]);
        });
      }
    },
    autocompleteSelect({ value, item, settingItem }) {
      if (settingItem.keyword === 'payName') {
        const selectItem = _.cloneDeep(value);
        let key = ['payName', 'payNum', 'tel'];
        if (this.accountType === 1) {
          key = key.concat(['identityNumber']);
        } else {
          key = key.concat(['bank', 'province', 'subBank']);
        }
        for (const i of key) {
          this.$set(item, i, selectItem[i]);
        }
        this.$nextTick(() => {
          this.$emit('changeValue', this.value);
        });
      }
    },
    changeInputNumberData({ item, key }) {
      /**
       * 对公银行账户（accountType===2）：实付金额=达人到手金额
       * 对公其他账户（accountType===3）：实付金额=达人到手金额
       * 第三方账户（accountType===1）：实付金额=达人到手金额 * 费率
       */
      if ([2, 3].includes(this.accountType)) {
        if (item.collectMoneyType === 0 && (key === 'settlementAmount' || key === 'priceRate')) {
          // 计算实付金额
          if (!item['settlementAmount'] && item['settlementAmount'] !== 0) {
            this.$set(item, 'actualAmount', '');
          } else {
            const settlementAmount = item['settlementAmount'] || 0;
            const num = Number(settlementAmount);
            const ans = parseFloat(((Math.round(num * 100)) / 100).toFixed(2));
            this.$set(item, 'actualAmount', ans);
          }
        }
      } else {
        /**
         *  ①当选择请款类型为全款 collectMoneyType: 0
         *  实付金额=结算金额   actualAmount = settlementAmount
         *  达人到手金额=实付金额/费率 withdrawAmount = actualAmount/priceRate
         */
        if (item.collectMoneyType === 0) { // 请款类型为全款
          if (key === 'settlementAmount' || key === 'priceRate') {
            // 计算实付金额
            if (!item['settlementAmount'] && item['settlementAmount'] !== 0) {
              this.$set(item, 'actualAmount', '');
            } else {
              const settlementAmount = item['settlementAmount'] || 0;
              const num = Number(settlementAmount);
              const ans = parseFloat(((Math.round(num * 100)) / 100).toFixed(2));
              this.$set(item, 'actualAmount', ans);
            }
            // 限制费率不能为零
            if (!item['priceRate'] || (item['priceRate'] && Number(item['priceRate']) === 0)) {
              this.$set(item, 'priceRate', '');
              this.$message.error('无费率的正常值为1.0');
              return;
            }
            // 计算达人到手金额
            if ((!item.actualAmount && item.actualAmount !== 0 && !item['priceRate'])) {
              this.$set(item, 'withdrawAmount', '');
            } else {
              const actualAmount = item['actualAmount'] || 0;
              const priceRate = item['priceRate'] || 0;
              const num = Number(actualAmount) / Number(priceRate);
              const ans = parseFloat(((Math.round(num * 100)) / 100).toFixed(2));
              this.$set(item, 'withdrawAmount', ans);
            }
            // end
          }
        } else {
          /**
           * ①当选择请款类型为预付款、部分款、尾款 collectMoneyType !== 0
           * 当修改达人到手金额，实付金额=达人到手金额*费率  actualAmount = withdrawAmount * priceRate
           * 当修改费率，实付金额=达人到手金额*费率
           * 当修改实付金额，达人到手金额=实付金额/费率
          */
          if (key === 'withdrawAmount' || key === 'priceRate') {
            // 限制费率不能为零
            if (item['priceRate'] && Number(item['priceRate']) === 0) {
              this.$set(item, 'priceRate', '');
              this.$message.error('无费率的正常值为1.0');
              return;
            }
            if (!item.withdrawAmount && item.withdrawAmount !== 0 && !item['priceRate'] && item['priceRate'] !== 0) {
              this.$set(item, 'actualAmount', '');
            } else {
              const withdrawAmount = item['withdrawAmount'] || 0;
              const priceRate = item['priceRate'] || 0;
              const num = Number(withdrawAmount) * Number(priceRate);
              const ans = parseFloat(((Math.round(num * 100)) / 100).toFixed(2));
              this.$set(item, 'actualAmount', ans);
            }
          } else if (key === 'actualAmount') {
            if (!item.actualAmount && item.actualAmount !== 0 && !item['priceRate'] && item['priceRate'] !== 0) {
              this.$set(item, 'withdrawAmount', '');
            } else {
              const actualAmount = item['actualAmount'] || 0;
              const priceRate = item['priceRate'] || 0;
              const num = Number(actualAmount) / Number(priceRate);
              const ans = parseFloat(((Math.round(num * 100)) / 100).toFixed(2));
              this.$set(item, 'withdrawAmount', ans);
            }
          }
        }
      }
      // 如果结算金额和实付金额不一致，需要警告
      if (this.isNumberNotEmpty(item.actualAmount) &&
          this.isNumberNotEmpty(item.settlementAmount) &&
          Number(item.actualAmount) !== Number(item.settlementAmount)) {
        this.$set(item, '_cellClass', {
          actualAmount: 'isWarning'
        });
      } else {
        this.$set(item, '_cellClass', {});
      }
      this.$nextTick(() => {
        this.$emit('changeValue', this.value);
      });
    },
    isNumberNotEmpty(num) { return num || num === 0; },
    // 获取下单平台的列表
    async platformList() {
      try {
        const result = await platformList();
        result.data.forEach(i => {
          i.name = i.value;
        });
        this.accountType1.forEach(i => {
          if (i.label === '下单平台') {
            this.$set(i, 'options', result.data);
          }
        });
        this.accountType2.forEach(i => {
          if (i.label === '下单平台') {
            this.$set(i, 'options', result.data);
          }
        });
      } catch (error) {
        console.log(error);
      }
    },
    exportBeforeExport() {
      if (this.$refs.btnGroupRef) {
        this.$refs.btnGroupRef.btnExport({ id: this.examinId });
      }
    },
    templateDownload() {
      if (this.$refs.btnGroupRef2) {
        this.$refs.btnGroupRef2.btnExport({ accountType: this.accountType }, '是否下载模板？');
      }
    },
    upProgress() {
      this.importLoading = true;
    },
    importCallback(data) {
      this.importLoading = false;
      if (data && data.data.length > 0) {
        data.data.forEach(i => {
          if (i.collectMoneyType) {
            i.collectMoneyType = Number(i.collectMoneyType);
          }
          if (i.settlementAmount || i.settlementAmount === 0) {
            i.settlementAmount = Number(i.settlementAmount) / 100;
          }
          if (i.withdrawAmount || i.withdrawAmount === 0) {
            i.withdrawAmount = Number(i.withdrawAmount) / 100;
          }
          if (i.actualAmount) {
            i.actualAmount = Number(i.actualAmount) / 100;
          }
          this.isDisabled(i);
        });
        if (this.value.length > 0) {
          const arr = this.value.concat(data.data);
          this.$emit('changeValue', arr);
          this.handlePriceRate(arr);
        } else {
          this.$emit('changeValue', data.data);
          this.handlePriceRate(data.data);
        }
      }
      this.$message.success('导入成功');
    },
    handlePriceRate(arr = []) {
      arr.forEach((item, index) => {
        if (index !== 0) {
          item.priceRate = arr[0].priceRate;
          this.changeInputNumberData({ item, key: 'priceRate' });
        }
      });
    },
    // 一键填单
    autoFill() {
      const params = {
        settleId: this.settleId
      };
      if (document.getElementById('check-autofill')) {
        document.getElementById('check-autofill').checked = true;
      }
      // '0': '渠道订单', '1': '项目订单', '2': '商务订单', '3': '营销授权', '4': '电商销售', '5': '项目渠道单'
      let titleMsg = '';
      let msg = '';
      if ((this.costBelong === 0 || this.costBelong === 5) && this.requestFundsType === 0) {
        titleMsg = '请确定是否一键填充账号和金额';
        msg = '合并相同账号的结算金额';
      }
      if ((this.costBelong === 0 || this.costBelong === 5) && this.requestFundsType === 1) {
        titleMsg = '请确定是否一键填充成本说明和金额';
        msg = '合并相同账号的结算金额和成本说明';
      }
      if (!(this.costBelong === 0 || this.costBelong === 5)) {
        titleMsg = '请确定是否一键填充成本说明和金额';
        msg = '合并所有成本金额和成本说明';
      }
      showModal(`
        <div>${titleMsg}</div>
        <div>注意：填充后将覆盖原有的值</div>
        <div style="display:flex;align-items:center;margin-top: 10px;justify-content: center;">
          <div style="cursor:pointer;">
            <input id="check-autofill" type="checkbox" checked="checked" >
          </div>
          <label for="check-autofill" style="font-size:14px;color: #333;font-weight: normal;margin-left:5px;cursor:pointer;">${msg}</label>
        </div>
      `, {
        dangerouslyUseHTMLString: true
      }).then((data) => {
        const checked = document.getElementById('check-autofill').checked;
        if (!params.settleId && this.selectCost && this.selectCost.length) {
          const selectCost = _.cloneDeep(this.selectCost);
          let orderList = [];
          selectCost.forEach(i => {
            orderList = orderList.concat(i.orderIds);
          });
          if (!orderList.length) return;
          if (checked) {
            // 合并相同账号的结算金额
            this.mergeFillContent(orderList);
          } else {
            this.fillContent(orderList);
          }
        } else if (params.settleId) {
          autoFillList(params).then((res) => {
            if (res.code === 200) {
              if (checked) {
              // 合并相同账号的结算金额
                this.mergeFillContent(res.data);
              } else {
                this.fillContent(res.data);
              }
            }
          });
        }
      });
    },
    // 全部填充
    fillContent(data) {
      const ans = [];
      // const requestFundsType = this.requestFundsType;
      // 请款类型为其他请款时填充说明
      data.forEach(i => {
        const obj = {
          ...this.initColletMoneyData,
          platformId: i.orderPlatformId,
          channelAccount: i.resourceName,
          remark: i.costDescription || ''
        };
        if (i.costPrice || i.costPrice === 0) {
          obj.settlementAmount = i.costPrice / 100;
          // 计算其他价格
          this.changeInputNumberData({ item: obj, key: 'settlementAmount' });
          // 计算其他价格 end
        }
        ans.push(obj);
      });
      this.$nextTick(() => {
        this.$emit('changeValue', ans);
      });
    },
    // 合并填充
    mergeFillContent(data) {
      const ans = [];
      data.forEach(i => {
        let someItem;
        if (this.costBelong === 0 || this.costBelong === 5) {
          someItem = ans.find(j => {
            return j.resourceName === i.resourceName && j.orderPlatformId === i.orderPlatformId;
          });
        } else {
          someItem = ans[0] || null;
        }

        if (someItem) {
          someItem.costPrice = math.add(Number(i.costPrice), Number(someItem.costPrice));
          if (someItem.costDescription || i.costDescription) {
            if (!someItem.costDescription) {
              someItem.costDescription = i.costDescription;
            } else {
              someItem.costDescription = `${someItem.costDescription}${i.costDescription ? '/' + i.costDescription : ''}`;
            }
          }
        } else {
          ans.push(i);
        }
      });
      this.fillContent(ans);
    },
    /**
     * 编辑说明
     */
    closeDialog() {
      this.dialogEditVisible = false;
      this.editRemarkData = {};
    },
    openEditDialog({ scope }) {
      this.editRemarkData = {
        remark: scope.row.remark,
        collectMoneyId: scope.row.id
      };
      this.dialogEditVisible = true;
    },
    edit() {
      if (!this.editRemarkData.remark) {
        ElMessage.error('请输入收款人说明');
        return;
      }
      this.editRemarkData.id = this.examinId;
      editColletMoneyList(this.editRemarkData).then(res => {
        if (res.code === 200) {
          this.$emit('getInfo', this.editRemarkData.id);
          this.$message.success('编辑成功');
          this.closeDialog();
        } else {
          ElMessage.error(res.message);
        }
      });
    },
    setLogText(arr) {
      arr.forEach(i => {
        i._logText = `付款申请${this.widthdrawInfo.settleName}的收款信息${i.payName}的收款账号`;
      });
      return arr;
    },
    rateInputChange(row, key) {
      if (key !== 'priceRate') return;
      this.value.forEach((item, index) => {
        if (index !== 0) {
          item[key] = row[key];
          this.changeInputNumberData({ item, key });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.collet-container {
  margin-top: 14px;
  &::v-deep {
    .isWarning {
      position: relative;
      .el-input__inner {
        border-color: red !important;
      }
      &::before {
        position: absolute;
        content: '实付金额与结算金额未一致';
        color: red;
        left: -7px;
        bottom: -4px;
        font-size: 12px;
        z-index: 1;
        transform: scale(0.8);
        white-space: nowrap;
      }
    }
  }
}
.mt10 {
  margin-top: 10px !important;
}
.supplier-import-btn {
  cursor: pointer;
  height: 32px;
  width: 80px;
  margin-left: 10px;
  position: relative;
  font-size: 14px;
  color: #666666;
  display: flex;
  align-items: center;
  border: 1px solid #DDDDDD;
  border-radius: 4px;
  justify-content: center;
}
.edit-main {
  margin: 16px 0;
}
.edit-dialog-btn {
  display: flex;
  align-items: center;
  justify-content: center;
}
.mobile-page-dialog {
  &::v-deep {
    .el-dialog {
      width: 76% !important;
    }
  }
}
.tip-container {
  margin-left: 10px;
  @include flexStyle($align:center);
  .text {
    font-size: 12px;
    margin-left: 5px;
    color: #666666;
  }
}
.third-cell {
  &::v-deep {
    .data-item {
      flex-basis: 30%;
    }
  }
}
</style>
